package leetcode;

import leetcode.*;
/**
 * Created by tizzybec on 6/26/2016.
 */
public class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode left = l1;
        ListNode right = l2;
        ListNode result = new ListNode(0);
        ListNode r = result;
        int carry = 0;
        while (left != null || right != null) {
            int val = (left != null ? left.val : 0) + (right != null ? right.val : 0) + carry;
            r.val = val % 10;
            carry =  val / 10;
            left = (left != null ? left.next : null);
            right = (right != null ? right.next : null);
            if (left != null || right != null) {
                r = r.next = new ListNode(0);
            } else if (carry > 0) {
                r.next = new ListNode(carry);
            }
        }
        return result;
    }
}
